package ar.edu.itba.it.raytracer.scene

import scala.math.{ pow, min }
import ar.edu.itba.it.raytracer.engine.{ Ray, Vector, Color }
import scala.math.sqrt

case class Sphere(center: Vector, radius: Double) extends Geom {
  def normal(poi: Vector, ray: Ray): Vector = (poi - center).normalized
  def intersect(ray: Ray): Option[Vector] = {
    var result: Option[Vector] = None
    val a = pow(ray.direction.norm1, 2)
    val b = 2 * ((ray.origin - center) * ray.direction)
    val c = pow((ray.origin - center).norm1, 2) - pow(radius, 2)
    val disc = pow(b, 2) - 4 * a * c
    if (disc > 0) {
      val v = sqrt(disc)
      var ts = List((-b + v) / (2 * a), (-b - v) / (2 * a)).filter(_ > 0).sorted
      if (!ts.isEmpty) result = Some(ray.origin + (ray.direction * ts(0)))
    }
    result
  }
}